from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_wtf.csrf import CSRFProtect
import logging
from logging.handlers import RotatingFileHandler
from app.config import config_map


db = SQLAlchemy()
csrf = CSRFProtect()

# 登录对象
login_manager = LoginManager()
login_manager.login_message = ''

# admin.login登录视图
login_manager.login_view = "admin.login"
login_manager.session_protection = "strong"

logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
rotating_fileHandler = RotatingFileHandler(filename="logs/log.txt", maxBytes=1024 * 1024 * 2, backupCount=10)
logging.getLogger().addHandler(rotating_fileHandler)

def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config_map.get(config))

    # 初始化session
    db.init_app(app)
    # csrf token验证
    csrf.init_app(app)

    login_manager.init_app(app)

    with app.app_context():
        from app.test_data import init_table_data
        # init_table_data(db)

    # 注意：导入蓝图的位置
    from app.controller import register_blueprint
    register_blueprint(app)

    # 注册全局函数
    from app.functions import register_func
    register_func(app)

    return app

